package com.jcli.file;

import java.io.*;
import java.util.Properties;

public class TextReplacement {
    public static void main(String[] args) {
        String inputFilePath = "src/main/resources/input.txt";
        String outputFilePath = "src/main/resources/output.txt";
        String propertiesFilePath = "src/main/resources/config.properties";


        try {
            // 读取替换规则
            Properties properties = new Properties();
            properties.load(new FileInputStream(propertiesFilePath));
            String replaceFrom = properties.getProperty("replace.from");
            String replaceTo = properties.getProperty("replace.to");

            // 读取文本
            StringBuilder textBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    textBuilder.append(line).append(System.lineSeparator());
                }
            }

            String text = textBuilder.toString();

            if (replaceFrom != null && replaceTo != null) {
                text = text.replace(replaceFrom, replaceTo);
            } else {
                System.out.println("替换规则为空，无法执行替换。");
            }


            // 保存修改后的文本到output.txt
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
                writer.write(text);
            }

            System.out.println("文本替换完成并保存到 " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }}
}
